package com.min.star.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.min.star.model.Curriculum;
import com.min.star.model.Grade;
import com.min.star.model.Student;
import com.min.star.model.Systeminfo;
import com.min.star.service.ICurriculumService;
import com.min.star.service.IGradeService;
import com.min.star.service.IStudentService;
import com.min.star.service.ISysteminfoService;
import com.min.star.ui.Json;

@Controller
@RequestMapping("/grade")
public class GradeController {

	@Autowired
	private IGradeService gradeService;
	
	@Autowired
	private IStudentService studentService;
	
	@Autowired
	private ICurriculumService curriculumService;
	
	@Autowired
	private ISysteminfoService systeminfoService;
	
	@RequestMapping("/open")
	public String open(Model model,HttpServletRequest request) {
		Systeminfo systeminfo = (Systeminfo) request.getSession().getAttribute("systeminfos");
		List<Systeminfo> info = this.systeminfoService.selectSystemList();
		List<Student> students = this.studentService.selectStudentList();
		List<Curriculum> curriculums = this.curriculumService.selectCurriculumList();
		model.addAttribute("systeminfo", info.get(0));
		System.out.println(info);
		model.addAttribute("students", students);
		System.out.println(students);
		model.addAttribute("curriculums", curriculums);
		System.out.println(curriculums);
		return "/teacher/examTeacherList";
	}
	
	@RequestMapping("/query")
	public String query(Model model) {
		return "/student/examStudentList";
	}
	
	@RequestMapping("/map")
	@ResponseBody // 将方法返回值序列化为json
	public Object map(Grade grade) {
//		通过page对象设置查询条件,指定分页的页码和页的大小
		Page<Grade> page = new Page<Grade>(grade.getPageNumber(), grade.getPageSize());
//		通过page条件查询出来的记录存放在另一个page中
//		Page<Grade> pager = this.gradeService.selectPage(page);
		Page<Grade> pager = this.gradeService.findPage(page,grade);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", pager.getRecords());
		map.put("total", pager.getTotal());
		System.out.println(map.toString());
		return map;
	}
	
	@RequestMapping("/delete/{ids}")
	@ResponseBody // 将方法返回值序列化为json
	public Object delete(@PathVariable("ids") String gradeIds) {
		Json json = new Json();
		int ret = this.gradeService.delete(gradeIds);
		if(ret > 0) {
			json.setMsg("删除成功！");
			json.setCode(0);
		}else {
			json.setMsg("删除失败！");
			json.setCode(-1);
		}
		return json;
	}
	
	@RequestMapping("/add")
	@ResponseBody // 将方法返回值序列化为json
	public Object add(@Valid Grade grade,BindingResult result,Model model) {
		List<Student> students = this.studentService.selectStudentList();
		List<Curriculum> curriculums = this.curriculumService.selectCurriculumList();
		model.addAttribute("students", students);
		model.addAttribute("curriculums", curriculums);
		Json json = new Json();
//		服务端验证
		if (result.hasErrors()) {
			return validMessage(result, json);
		}
		boolean exist4grade = this.gradeService.checkgradeExist4Add(grade);
		if ( exist4grade) {
			json.setMsg("该学生的该门课程成绩已经存在，请勿重新添加！");
			json.setCode(-1);
		} else {
			Grade info = this.gradeService.save(grade);
			json.setMsg("添加成功");
			json.setCode(0);
			json.setObj(info);
		}
		return json;
	}
	
	@RequestMapping("/edit")
	@ResponseBody // 将方法返回值序列化为json
	public Object edit(@Valid Grade grade,BindingResult result) {
		Json json = new Json();
//		服务端验证
		if (result.hasErrors()) {
			return validMessage(result, json);
		}
		int ret = this.gradeService.update(grade);
		if ( ret>0) {
			Grade info = this.gradeService.findById(grade.getId());
			json.setMsg("该学生的该门课程成绩更新成功！");
			json.setCode(0);
			json.setObj(info);
		} else {
			json.setMsg("更新失败");
			json.setCode(-1);
		}
		return json;
	}
	
	private Object validMessage(BindingResult result, Json j) {
		String msg="";
		List<ObjectError> allErrors = result.getAllErrors();
		if(allErrors!=null && allErrors.size()>0) {
			for(int i=0;i<allErrors.size();i++) {
				ObjectError error = allErrors.get(i);
				if(i == 0) {
					msg += error.getDefaultMessage() + "<br/>";
				}else {
					msg += "<i class='mdi mdi-emoticon-sad'></i>" + error.getDefaultMessage() + "<br/>";
				}
			}
		}
		j.setMsg(msg);
		j.setCode(-1);
		j.setObj(allErrors);
		return j;
	}
	
}
